﻿using System.Collections.Generic;

namespace UnityView
{
    public class Algorithm
    {
        public static int BinarySearchFloat(List<float> sortedArray, float value)
        {
            return BinarySearchFloat(sortedArray, 0, sortedArray.Count, value);
        }

        public static int BinarySearchFloat(float[] sortedArray, float value)
        {
            return BinarySearchFloat(sortedArray, 0, sortedArray.Length, value);
        }

        /// <summary>
        /// 二分查找目标值在给定有序数组中的位置
        /// </summary>
        /// <param name="sortedArray">数据源，浮点数组，必须是有序数组</param>
        /// <param name="start">起始下标</param>
        /// <param name="end">结束下标</param>
        /// <param name="value">目标值</param>
        /// <returns>位置下标</returns>
        public static int BinarySearchFloat(List<float> sortedArray, int start, int end, float value)
        {
            if (start == end) return start;
            if (value < sortedArray[start]) return -1;
            while (end - start != 1)
            {
                var current = (end + start) >> 1;
                if (value >= sortedArray[current])
                {
                    start = current;
                }
                else
                {
                    end = current;
                }
            }
            return start;
        }

        public static int BinarySearchFloat(float[] sortedArray, int start, int end, float value)
        {
            if (start == end) return start;
            if (value < sortedArray[start]) return -1;
            while (end - start != 1)
            {
                var current = (end + start) >> 1;
                if (value >= sortedArray[current])
                {
                    start = current;
                }
                else
                {
                    end = current;
                }
            }
            return start;
        }
    }
}
